﻿using Contrib.BSNavigation.Models;
using Orchard.Commands;
using Orchard.ContentManagement;
using Orchard.Core.Navigation.Models;
using Orchard.Core.Navigation.Services;

namespace Contrib.BSNavigation.Commands
{
    public class MenuCommands : DefaultOrchardCommandHandler {
        private readonly IContentManager _contentManager;
        private readonly IMenuService _menuService;

        public MenuCommands(IContentManager contentManager, IMenuService menuService) {
            _contentManager = contentManager;
            _menuService = menuService;
        }

        [OrchardSwitch]
        public string MenuPosition { get; set; }

        [OrchardSwitch]
        public string MenuText { get; set; }

        [OrchardSwitch]
        public string DataSectionValue { get; set; }

        [OrchardSwitch]
        public string MenuName { get; set; }

        [CommandName("menu datasectionlink create")]
        [CommandHelp("menu datasectionlink create /MenuPosition:<position> /MenuText:<text> /DataSectionValue:<datasectionvalue> /MenuName:<name>\r\n\t" + "Creates a new Data-Section link menu item")]
        [OrchardSwitches("MenuPosition,MenuText,DataSectionValue,MenuName")]
        public void Create() {
            // flushes before doing a query in case a previous command created the menu
            _contentManager.Flush();

            var menu = _menuService.GetMenu(MenuName);

            if(menu == null) {
                Context.Output.WriteLine(T("Menu not found.").Text);
                return;
            }

            var menuItem = _contentManager.Create("DataSectionLink");
            var menuPart = menuItem.As<MenuPart>();
            var dataSectionLinkPart = menuItem.As<DataSectionLinkPart>();
            menuPart.MenuPosition = MenuPosition;
            menuPart.MenuText = T(MenuText).ToString();
            menuPart.Menu = menu.ContentItem;
            dataSectionLinkPart.DataSectionValue = DataSectionValue;
            Context.Output.WriteLine(T("DataSectionLink menu item created successfully.").Text);
        }
    }
}